package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.product;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.PdtPlanDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.PlanDetailBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.StatisticPlanBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PdtPlanDetailExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PdtPlanExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CPdtPlanExMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.mapper.CWeightSheetsMapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetAllPdtPlanVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetPdtPlanDetailVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.UserInfoVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;

@Component
public class PdtPlanBu {

    @Autowired
    private ICPdtPlanExService iCPdtPlanExService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private CPdtPlanExMapper cPdtPlanExMapper;
    @Autowired
    private PdtPlanDic pdtPlanDic;
    @Autowired
    private ICCompanysService companysService;
    @Autowired
    private ICProductsInfoService productsInfoService;
    @Autowired
    private CWeightSheetsMapper weightSheetsMapper;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ITApproveInfoService approveInfoService;


    //    查询所有PdtPlan
    public SzResult getAllPdtPlan(StatisticPlanBo param, String id,String plantId) throws Exception {
        param.setDataFrom( plantId);
        return SzResult.success(iCPdtPlanExService.statisticPlan(param));
    }

    //    查询发货计划详情
    public SzResult getPdtPlanDetail(PlanDetailBo param, String id,String plantId) throws Exception {
        param.setDataFrom( plantId);
        return SzResult.success(iCPdtPlanExService.queryPdtPlanEx(param));
    }

    //          新增发货计划时，先查询是否在时间区间内有重复的发货计划
    //    新增发货计划
    public SzResult addPdtPlanDetail(PlanDetailBo param, String id, String plantId) throws Exception {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String pdtId = param.getPdtId();
        String coId = param.getCoId();
        String planType = param.getPlanType();

        // 查询产品信息
        CProductsInfo productsInfo = productsInfoService.getOne(new QueryWrapper<CProductsInfo>().eq("ID", pdtId));
        if (productsInfo == null) {
            return SzResult.error("产品不存在");
        }
        String pdtinfPdt = productsInfo.getPdtinfPdt();

        // 查询公司信息
        CCompanys companys = companysService.getOne(new QueryWrapper<CCompanys>().eq("ID", coId));
        if (companys == null) {
            return SzResult.error("公司不存在");
        }
        String cpyCo = companys.getCpyCo();
        String cpyChiCo = companys.getCpyChico();

        // 查询是否存在重叠的发货计划
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime planStartDateTime = LocalDateTime.parse(param.getPlanStartDate(), formatter);
        LocalDateTime planEndDateTime;
        int planDaysInt = param.getPlanDays(); // 获取Integer类型的计划天数
        String planDaysStr = String.valueOf(planDaysInt); // 转换为String类型
        if (planDaysInt == 1) {
            planEndDateTime = planStartDateTime.withHour(23).withMinute(59).withSecond(59);
        } else {
            planEndDateTime = planStartDateTime.plusDays(planDaysInt - 1).withHour(23).withMinute(59).withSecond(59);
        }

        List<CPdtPlanEx> cPdtPlanExList = iCPdtPlanExService.list(
                new QueryWrapper<CPdtPlanEx>()
                        .eq("PDT_PLANEX_PDTID", pdtId)
                        .eq("PDT_PLANEX_COID", coId)
                        .ge("PDT_PLANEX_BEGIN", planStartDateTime)
                        .le("PDT_PLANEX_END", planEndDateTime)
        );
        if (!cPdtPlanExList.isEmpty()) {
            return SzResult.error("该时间段内已有发货计划");
        }

        // 创建发货计划实体
        CPdtPlanEx cPdtPlanEx = new CPdtPlanEx();
        cPdtPlanEx.setId(uuid);
        QueryWrapper<CPdtPlanEx> pdtPlanExQueryWrapper = new QueryWrapper<>();
        pdtPlanExQueryWrapper.orderByDesc("PDT_PLANEX_ID");
        pdtPlanExQueryWrapper.last("limit 1");
        pdtPlanExQueryWrapper.eq("DATA_FROM", plantId);
        CPdtPlanEx cPdtPlanEx2 = iCPdtPlanExService.getOne(pdtPlanExQueryWrapper);
        if (cPdtPlanEx2 != null) {
            BigDecimal pdtPlanexId = cPdtPlanEx2.getPdtPlanexId();
            String pdtPlanexId1 = String.valueOf((pdtPlanexId.intValue() + 1));
            cPdtPlanEx.setPdtPlanexId(new BigDecimal(pdtPlanexId1));
        } else {
            cPdtPlanEx.setPdtPlanexId(new BigDecimal(1));
        }
        cPdtPlanEx.setPdtPlanexCoid(coId);
        cPdtPlanEx.setPdtPlanexPdtid(pdtId);
        cPdtPlanEx.setPdtPlanexType(Integer.valueOf(planType));
        cPdtPlanEx.setPdtPlanexNum(param.getPlanNum());
        cPdtPlanEx.setPdtPlanexTmLimt(BigDecimal.valueOf(Long.parseLong(planDaysStr))); // 使用转换后的String类型
        cPdtPlanEx.setPdtPlanexBegin(planStartDateTime);
        cPdtPlanEx.setPdtPlanexEnd(planEndDateTime);
        SysUser user = userInfoDao.getUser(id);
        cPdtPlanEx.setPdtPlanexOperator(user.getTrueName());
        cPdtPlanEx.setPdtPlanexDeleted(0);
        cPdtPlanEx.setDataFrom(plantId);
        cPdtPlanEx.setDownedID1(0);

        // 审批逻辑
        TApprove tApprove = approveService.getOne(
                new QueryWrapper<TApprove>()
                        .eq("IF_ON", 1)
                        .eq("DEL_FLAG", 0)
                        .eq("DATA_FROM", plantId)
                        .eq("APPROVE_NAME", "addDeliveryPlan")
        );
        if (tApprove != null) {
            // 构建并保存审批信息
            TApproveInfo tApproveInfo = buildAndSaveApproveInfo(user, cpyCo, cpyChiCo, pdtinfPdt, planType, param, plantId);
            return SzResult.Error("该功能需审批,请等待审批");
        }

        // 保存发货计划信息
        iCPdtPlanExService.save(cPdtPlanEx);
        // 记录日志
        sysLogBu.logRecord("新增发货计划", user.getTrueName(),
                "新增一条" + cpyCo + "." + cpyChiCo + "公司的" + pdtinfPdt + "品种的发货计划,计划类型是:" + planType + " 计划天数是:" + planDaysStr + " 计划量是:" + param.getPlanNum() + "计划开始时间是:" + planStartDateTime, plantId);
        return SzResult.Success();
    }


    private TApproveInfo buildAndSaveApproveInfo(SysUser user, String cpyCo, String cpyChiCo, String pdtinfPdt, String planType, PlanDetailBo param, String plantId) {
        TApproveInfo tApproveInfo = new TApproveInfo();
        tApproveInfo.setApproveId(approveService.getOne(new QueryWrapper<TApprove>().eq("IF_ON", 1).eq("DEL_FLAG", 0).eq("DATA_FROM", plantId).eq("APPROVE_NAME", "addDeliveryPlan")).getId());
        tApproveInfo.setApproveTier(approveService.getOne(new QueryWrapper<TApprove>().eq("IF_ON", 1).eq("DEL_FLAG", 0).eq("DATA_FROM", plantId).eq("APPROVE_NAME", "addDeliveryPlan")).getApproveTier());
        tApproveInfo.setApproveState(0);
        tApproveInfo.setCreateBy(user.getTrueName());
        tApproveInfo.setCreateTime(LocalDateTime.now());
        tApproveInfo.setDelFlag(0);
        tApproveInfo.setApproveRemark("");
        String approveInfoMessage = "由【" + user.getTrueName() + "】发起的新增发货计划审批：【新增一条" + cpyCo + "." + cpyChiCo + "公司的" + pdtinfPdt + "品种的发货计划,计划类型是:" + planType + " 计划天数是:" + param.getPlanDays() + " 计划量是:" + param.getPlanNum() + "计划开始时间是:" + LocalDateTime.parse(param.getPlanStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "】";
        tApproveInfo.setApproveInfo(approveInfoMessage);
        tApproveInfo.setDataFrom(plantId);
        Map<String, Object> map = new HashMap<>();
        // 省略map填充，直接使用审批信息构建
        String executionData = JSON.toJSONString(map);
        tApproveInfo.setExecutionData(executionData);
        approveInfoService.save(tApproveInfo);
        return tApproveInfo;
    }

    //修改发货计划
    public SzResult updatePdtPlanDetail(PlanDetailBo param, String id,String plantId) throws Exception {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        UpdateWrapper<CPdtPlanEx> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ID", param.getId());
        updateWrapper.set("DownedID1", 0);
        CPdtPlanEx cPdtPlanEx = new CPdtPlanEx();
        String planType1 = param.getPlanType();
        cPdtPlanEx.setPdtPlanexType(Integer.valueOf(planType1));
        cPdtPlanEx.setPdtPlanexNum(param.getPlanNum());
        cPdtPlanEx.setPdtPlanexTmLimt(BigDecimal.valueOf(Long.parseLong(param.getPlanDays().toString())));
        LocalDateTime planStartDateTime = LocalDateTime.parse(param.getPlanStartDate(), formatter);
        LocalDateTime planEndDateTime;
        int planDaysInt = param.getPlanDays(); // 获取Integer类型的计划天数
        String planDaysStr = String.valueOf(planDaysInt); // 转换为String类型
        if (planDaysInt == 1) {
            planEndDateTime = planStartDateTime.withHour(23).withMinute(59).withSecond(59);
        } else {
            planEndDateTime = planStartDateTime.plusDays(planDaysInt - 1).withHour(23).withMinute(59).withSecond(59);
        }
        cPdtPlanEx.setPdtPlanexBegin(planStartDateTime);
//        PDT_PLANEX_END为计划结束日期，根据计划开始日期和计划天数计算得出
        cPdtPlanEx.setPdtPlanexEnd(planEndDateTime);
        SysUser user = userInfoDao.getUser(id);
       // String plantId = userInfoDao.getUserFactory(id).getId();
        cPdtPlanEx.setPdtPlanexOperator(user.getTrueName());
        cPdtPlanEx.setDataFrom(plantId);
//        查询这个计划以外是否有重复的发货计划
        QueryWrapper<CPdtPlanEx> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("ID", param.getId());
//        品种相同
        queryWrapper.eq("PDT_PLANEX_PDTID", param.getPdtId());
//        单位id相同
        queryWrapper.eq("PDT_PLANEX_COID", param.getCoId());
//        时间区间内：param.getPlanStartDate()加上param.getPlanDays()天在PdtPlanexBeginDate和PdtPlanexEndDate之间，是否使用apply方法使用sql语句
//param.getPlanStartDate()加上param.getPlanDays()
        LocalDateTime localDateTime = LocalDateTime.parse(param.getPlanStartDate(), formatter);
        localDateTime = localDateTime.plusDays(param.getPlanDays());
        queryWrapper.apply("(" + "(" + "PDT_PLANEX_BEGIN" + " >= " + "'" + param.getPlanStartDate() + "'" + " AND " + " PDT_PLANEX_BEGIN " + " <= " + "'" + localDateTime + "'" + " ) " + " or " +
                " ( " + " PDT_PLANEX_END " + " >= " + "'" + param.getPlanStartDate() + "'" + " AND " + " PDT_PLANEX_END " + " <= " + "'" + localDateTime + "'" + " ) " + " or " +
                " ( " + "PDT_PLANEX_BEGIN" + " <= " + "'" + param.getPlanStartDate() + "'" + " AND " + " PDT_PLANEX_END " + " >= " + "'" + localDateTime + "'" + " ) " + " or " +
                " ( " + " PDT_PLANEX_BEGIN " + " >=" + "'" + param.getPlanStartDate() + "'" + " AND " + " PDT_PLANEX_END " + " <= " + "'" + localDateTime + "'" + " ) " + ")");
        queryWrapper.eq("PDT_PLANEX_DELETED", 0);
        List<CPdtPlanEx> cPdtPlanExList = iCPdtPlanExService.list(queryWrapper);
//        if (!cPdtPlanExList.get(0).getPdtPlanexBegin().equals(LocalDateTime.parse(param.getPlanStartDate(),formatter)) && !cPdtPlanExList.get(0).getPdtPlanexEnd().equals(LocalDateTime.parse(param.getPlanStartDate(),formatter).plusDays(param.getPlanDays()))){
//            return SzResult.error("检测您修改了计划时间段后的时间区间存在发货计划交叉");
//        }
        if (cPdtPlanExList.size() > 1) {
            return SzResult.error("检测您修改了计划时间段后的时间区间存在发货计划交叉");
        }
//        如果改完后的计划
//        查询这个计划的结束时间是否小于当前时间，如果小于当前时间，不能修改
        QueryWrapper<CPdtPlanEx> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", param.getId());
        queryWrapper1.le("PDT_PLANEX_END", LocalDateTime.now());
        List<CPdtPlanEx> cPdtPlanExList1 = iCPdtPlanExService.list(queryWrapper1);
        if (!cPdtPlanExList1.isEmpty()) {
            return SzResult.error("该计划已经结束，不能修改");
        }
        cPdtPlanEx.setDownedID1(0);

        QueryWrapper<CPdtPlanEx> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("ID", param.getId());
        CPdtPlanEx cPdtPlanEx1 = iCPdtPlanExService.getOne(queryWrapper4);
        String pdtPlanexCoid = cPdtPlanEx1.getPdtPlanexCoid();
        String pdtPlanexPdtid = cPdtPlanEx1.getPdtPlanexPdtid();
        String planType = String.valueOf(cPdtPlanEx1.getPdtPlanexType());
        if (planType.equals("1")) {
            planType = "车数";
        } else {
            planType = "数量";
        }
        BigDecimal pdtPlanexNum = cPdtPlanEx1.getPdtPlanexNum();//计划量
        String pdtPlanexTmLimt = String.valueOf(cPdtPlanEx1.getPdtPlanexTmLimt());//天数
        LocalDateTime pdtPlanexBegin = cPdtPlanEx1.getPdtPlanexBegin();//计划开始时间
        QueryWrapper<CCompanys> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("ID", pdtPlanexCoid);
        CCompanys cCompanys = companysService.getOne(queryWrapper5);
        String cpyCo = cCompanys.getCpyCo();
        String cpyChiCo = cCompanys.getCpyChico();
        String cpy=cpyCo+cpyChiCo;
        QueryWrapper<CProductsInfo> queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.eq("ID", pdtPlanexPdtid);
        CProductsInfo cProductsInfo = productsInfoService.getOne(queryWrapper6);
        String pdtinfPdt = cProductsInfo.getPdtinfPdt();

        QueryWrapper<CCompanys> queryWrapper7 = new QueryWrapper<>();
        queryWrapper7.eq("ID", param.getCoId());
        CCompanys cCompanys1 = companysService.getOne(queryWrapper7);
        String cpyCo1 = cCompanys1.getCpyCo();
        String cpyChiCo1 = cCompanys1.getCpyChico();
        String cpy1=cpyCo1+cpyChiCo1;
        QueryWrapper<CProductsInfo> queryWrapper8 = new QueryWrapper<>();
        queryWrapper8.eq("ID", param.getPdtId());
        CProductsInfo cProductsInfo1 = productsInfoService.getOne(queryWrapper8);
        String pdtinfPdt1 = cProductsInfo1.getPdtinfPdt();
        if (planType1.equals("1")){
            planType1 = "车数";
        }else {
            planType1 = "数量";
        }
        BigDecimal pdtPlanexNum1 = param.getPlanNum();//计划量
        String pdtPlanexTmLimt1 = String.valueOf(param.getPlanDays());//天数
        LocalDateTime pdtPlanexBegin1 = LocalDateTime.parse(param.getPlanStartDate(), formatter);//计划开始时间
//将cpy和cpy1,pdtinfPdt和pdtinfPdt1,planType和planType1,pdtPlanexNum和pdtPlanexNum1,pdtPlanexTmLimt和pdtPlanexTmLimt1,pdtPlanexBegin和pdtPlanexBegin1进行比较,如果不同,就记入日志
        StringBuilder logMsg = new StringBuilder();
        if (!cpy.equals(cpy1)){
            logMsg.append("公司名称由").append(cpy).append("改为").append(cpy1).append(";");
        }
        if (!pdtinfPdt.equals(pdtinfPdt1)){
            logMsg.append("产品名称由").append(pdtinfPdt).append("改为").append(pdtinfPdt1).append(";");
        }
        if (!planType.equals(planType1)){
            logMsg.append("计划类型由").append(planType).append("改为").append(planType1).append(";");
        }
        if (!pdtPlanexNum.equals(pdtPlanexNum1)){
            logMsg.append("计划量由").append(pdtPlanexNum).append("改为").append(pdtPlanexNum1).append(";");
        }
        if (!pdtPlanexTmLimt.equals(pdtPlanexTmLimt1)){
            logMsg.append("天数由").append(pdtPlanexTmLimt).append("改为").append(pdtPlanexTmLimt1).append(";");
        }
        if (!pdtPlanexBegin.equals(pdtPlanexBegin1)){
            logMsg.append("计划开始时间由").append(pdtPlanexBegin).append("改为").append(pdtPlanexBegin1).append(";");
        }
        iCPdtPlanExService.update(cPdtPlanEx, updateWrapper);
        sysLogBu.logRecord("发货计划", user.getTrueName(), String.valueOf(logMsg), plantId);
        return SzResult.Success();
    }


    @Async
    public Future<List<PdtPlanExcelEn>> pdtPlanExportExcel(List<Map<String, Object>> fields, List<Map<String, Object>> ids, String filename, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, Map<String, String> form, String sheetName, HttpServletResponse response, StatisticPlanBo statisticPlanBo) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<PdtPlanExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PdtPlanExcelEn pdtPlanExcelEn = PdtPlanExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("pdtPlanexCo")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtPlanexCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexType")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtPlanexType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setSumNum(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtinfPdt")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtinfPdt(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setSumNum2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("countNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setCountNum(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtPlanExcelEn);
                    }
                    break;
                case "all":
                    List<GetAllPdtPlanVo> getAllPdtPlanVos = iCPdtPlanExService.statisticPlan(statisticPlanBo);
                    for (GetAllPdtPlanVo getAllPdtPlanVo : getAllPdtPlanVos) {
                        CCompanys companys = companysService.getById(getAllPdtPlanVo.getPdtPlanexCoId());

                        PdtPlanExcelEn pdtPlanExcelEn = PdtPlanExcelEn.builder()
                                .pdtPlanexCo(Optional.of(companys.getCpyCo()+"."+companys.getCpyChico()).map(Object::toString).orElse(""))
                                .pdtPlanexType(Optional.ofNullable(pdtPlanDic.planTypeDic(getAllPdtPlanVo.getPdtPlanexType())).map(Object::toString).orElse(""))
                                .sumNum(Optional.ofNullable(getAllPdtPlanVo.getSumNum()).map(Object::toString).orElse(""))
                                .pdtinfPdt(Optional.ofNullable(getAllPdtPlanVo.getPdtinfPdt()).map(Object::toString).orElse(""))
                                .sumNum2(Optional.ofNullable(getAllPdtPlanVo.getSumNum2()).map(Object::toString).orElse(""))
                                .countNum(Optional.ofNullable(getAllPdtPlanVo.getCountNum()).map(Object::toString).orElse(""))
                                .build();
                        list.add(pdtPlanExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PdtPlanExcelEn pdtPlanExcelEn = PdtPlanExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("pdtPlanexCo")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtPlanexCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexType")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtPlanexType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setSumNum(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtinfPdt")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setPdtinfPdt(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setSumNum2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("countNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanExcelEn.setCountNum(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtPlanExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }


    /**
     * 发货计划详情导出
     *
     * @param fields
     * @param ids
     * @param filename
     * @param isHeader
     * @param mode
     * @param original
     * @param pager
     * @param form
     * @param sheetName
     * @param response
     * @param
     * @return
     */

    @Async
    public Future<List<PdtPlanDetailExcelEn>> pdtPlanDetailExportExcel(List<Map<String, Object>> fields, List<Map<String, Object>> ids, String filename, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, Map<String, String> form, String sheetName, HttpServletResponse response, PlanDetailBo param) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<PdtPlanDetailExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PdtPlanDetailExcelEn pdtPlanDetailExcelEn = PdtPlanDetailExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("coName")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setCoName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexType")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexTmLimt")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexTmLimt(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setSumNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("countNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setCountNum(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexOperator")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexOperator(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprver")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprver(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprver2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprver2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexBegin")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexBegin(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexEnd")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexEnd(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexApprvTm")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprvTm(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprvTm2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprvTm2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprved")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprved(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprved2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprved2(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtPlanDetailExcelEn);
                    }
                    break;

                case "all":
                    QueryWrapper<CPdtPlanEx> wrapper = new QueryWrapper<>();
                    wrapper.eq("PDT_PLANEX_DELETED", 0);
                    wrapper.eq(param.getDataFrom() != null, "DATA_FROM", param.getDataFrom());
                    wrapper.eq(param.getCoId() != null && !param.getCoId().equals(""), "PDT_PLANEX_COID", param.getCoId());
                    if (StringUtils.isNotBlank(param.getPdtId())) {
                        wrapper.eq(param.getPdtId() != null && !param.getPdtId().equals(""), "PDT_PLANEX_PDTID", param.getPdtId());
                    }
                    wrapper.eq(param.getPlanType() != null && !param.getPlanType().equals(""), "PDT_PLANEX_TYPE", param.getPlanType());
                    if (StringUtils.isNotBlank(param.getMinDate()) && StringUtils.isNotBlank(param.getMaxDate())) {
                        wrapper.apply("(" + "(" + "PDT_PLANEX_BEGIN" + " >= " + "'" + param.getMinDate() + "'" + " AND " + " PDT_PLANEX_BEGIN " + " <= " + "'" + param.getMaxDate() + "'" + " ) " + " or " +
                                " ( " + " PDT_PLANEX_END " + " >= " + "'" + param.getMinDate() + "'" + " AND " + " PDT_PLANEX_END " + " <= " + "'" + param.getMaxDate() + "'" + " ) " + " or " +
                                " ( " + "PDT_PLANEX_BEGIN" + " <= " + "'" + param.getMinDate() + "'" + " AND " + " PDT_PLANEX_END " + " >= " + "'" + param.getMaxDate() + "'" + " ) " + " or " +
                                " ( " + " PDT_PLANEX_BEGIN " + " >=" + "'" + param.getMinDate() + "'" + " AND " + " PDT_PLANEX_END " + " <= " + "'" + param.getMaxDate() + "'" + " ) " + ")");
                    }
                    if (StringUtils.isNotBlank(param.getSortName())) {
                        if (StringUtils.isNotBlank(param.getSortString()) && param.getSortString().toUpperCase().equals("\n" +
                                "// DESC")) {
                            wrapper.orderByDesc(param.getSortName());
                        } else {
                            wrapper.orderByAsc(param.getSortName());
                        }
                    } else {
                        wrapper.orderByDesc("PDT_PLANEX_ID");
                    }
                    List<CPdtPlanEx> result = iCPdtPlanExService.list(wrapper);
                    ModelMapper mapper = new ModelMapper();
                    List<GetPdtPlanDetailVo> getPdtPlanDetailVos = mapper.map(result, new TypeToken<List<GetPdtPlanDetailVo>>() {
                    }.getType());
                    for (GetPdtPlanDetailVo getPdtPlanDetailVo : getPdtPlanDetailVos) {
                        QueryWrapper<CCompanys> wrapper1 = new QueryWrapper<>();
                        wrapper1.eq("ID", getPdtPlanDetailVo.getPdtPlanexCoid());
                        wrapper1.eq("CPY_DELETED", 0);
                        CCompanys cCompanys = companysService.getOne(wrapper1);
                        getPdtPlanDetailVo.setCoName(cCompanys.getCpyCo());
                        QueryWrapper<CProductsInfo> wrapper2 = new QueryWrapper<>();
                        wrapper2.eq("ID", getPdtPlanDetailVo.getPdtPlanexPdtid());
                        wrapper2.eq("PDTINF_DELETED", 0);
                        CProductsInfo cProductsInfo = productsInfoService.getOne(wrapper2);
                        getPdtPlanDetailVo.setPdtName(cProductsInfo.getPdtinfPdt());
                        Map map = weightSheetsMapper.getPlanWeight(cCompanys.getCpyCo(), cCompanys.getCpyChico(), cProductsInfo.getPdtinfPdt(), getPdtPlanDetailVo.getPdtPlanexBegin().toString(), getPdtPlanDetailVo.getPdtPlanexEnd().toString());
                        if (map.get("sum") != null && map.get("count") != null) {
                            getPdtPlanDetailVo.setSumNum(BigDecimal.valueOf(Double.parseDouble(map.get("sum").toString())));
                            getPdtPlanDetailVo.setCountNum(BigDecimal.valueOf(Double.parseDouble(map.get("count").toString())));
                        } else {
                            getPdtPlanDetailVo.setSumNum(BigDecimal.valueOf(0));
                            getPdtPlanDetailVo.setCountNum(BigDecimal.valueOf(0));
                        }
                    }
                    PdtPlanDetailExcelEn pdtPlanDetailExcelEn1 = PdtPlanDetailExcelEn.builder().build();
                    for (GetPdtPlanDetailVo getPdtPlanDetailVo : getPdtPlanDetailVos) {
                        pdtPlanDetailExcelEn1.setCoName(getPdtPlanDetailVo.getCoName());
                        pdtPlanDetailExcelEn1.setPdtName(getPdtPlanDetailVo.getPdtName());
                        pdtPlanDetailExcelEn1.setPdtPlanexType(String.valueOf(getPdtPlanDetailVo.getPdtPlanexType()));
                        pdtPlanDetailExcelEn1.setPdtPlanexTmLimt(String.valueOf(getPdtPlanDetailVo.getPdtPlanexTmLimt()));
                        pdtPlanDetailExcelEn1.setPdtPlanexNum(String.valueOf(getPdtPlanDetailVo.getPdtPlanexNum()));
                        pdtPlanDetailExcelEn1.setSumNum(String.valueOf(getPdtPlanDetailVo.getSumNum()));
                        pdtPlanDetailExcelEn1.setCountNum(String.valueOf(getPdtPlanDetailVo.getCountNum()));
                        pdtPlanDetailExcelEn1.setPdtPlanexBegin(String.valueOf(getPdtPlanDetailVo.getPdtPlanexBegin()));
                        pdtPlanDetailExcelEn1.setPdtPlanexEnd(String.valueOf(getPdtPlanDetailVo.getPdtPlanexEnd()));
                        pdtPlanDetailExcelEn1.setPdtPlanexOperator(getPdtPlanDetailVo.getPdtPlanexOperator());
                        pdtPlanDetailExcelEn1.setPdtPlanexApprver(getPdtPlanDetailVo.getPdtPlanexApprver());
                        pdtPlanDetailExcelEn1.setPdtPlanexApprver2(getPdtPlanDetailVo.getPdtPlanexApprver2());
                        pdtPlanDetailExcelEn1.setPdtPlanexApprvTm(String.valueOf(getPdtPlanDetailVo.getPdtPlanexApprvTm()));
                        pdtPlanDetailExcelEn1.setPdtPlanexApprvTm2(String.valueOf(getPdtPlanDetailVo.getPdtPlanexApprvTm2()));
                        pdtPlanDetailExcelEn1.setPdtPlanexApprved(String.valueOf(getPdtPlanDetailVo.getPdtPlanexApprved()));
                        pdtPlanDetailExcelEn1.setPdtPlanexApprved2(String.valueOf(getPdtPlanDetailVo.getPdtPlanexApprved2()));
                    }
                    list.add(pdtPlanDetailExcelEn1);
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        PdtPlanDetailExcelEn pdtPlanDetailExcelEn = PdtPlanDetailExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("coName")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setCoName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexType")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexTmLimt")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexTmLimt(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("sumNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setSumNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("countNum")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setCountNum(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexOperator")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexOperator(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprver")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprver(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprver2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprver2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexBegin")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexBegin(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexEnd")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexEnd(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtPlanexApprvTm")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprvTm(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprvTm2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprvTm2(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprved")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprved(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtPlanexApprved2")) {
                                if (entry.getValue() != null) {
                                    pdtPlanDetailExcelEn.setPdtPlanexApprved2(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtPlanDetailExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }

    public SzResult deletePdtPlan(String pdtPlanexId, String token) throws Exception {
        QueryWrapper<CPdtPlanEx> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDT_PLANEX_ID", pdtPlanexId);
        CPdtPlanEx one = iCPdtPlanExService.getOne(queryWrapper);
        one.setPdtPlanexDeleted(1);
        one.setDownedID1(0);
        iCPdtPlanExService.updateById(one);
        return SzResult.Success();
    }
}
